<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="类型：">
                            <el-select v-model="transferVal1" placeholder="请选择类型" style="width: 100%">
                                <el-option v-for="item in options1" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="岗位名称：">
                            <el-input v-model="transferVal2" placeholder="请输入岗位名称" />
                        </el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('jobResponsibilityLedger1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('jobResponsibilityLedger7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref='excelRef' :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="岗位名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="jobName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.jobName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="type" label="岗位类型" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="type" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="scope">
													<span v-if="scope.row.type == 1">办公</span>
													<span v-if="scope.row.type == 2">现场</span>
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新时间" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新人" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>
										<el-table-column min-width="160" :show-overflow-tooltip="false" label="操作" align="center" fixed="right">
											<el-table-column min-width="160" :show-overflow-tooltip="false" fixed="right" align="center">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button @click="editClick(scope.row.n_Id)" class="icon-e" icon="ele-View" size="small" text type="success"> 详情 </el-button>
														<el-button v-if="$hasPer('jobResponsibilityLedger2:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
														<el-button v-if="$hasPer('jobResponsibilityLedger3:delete')" @click="deleteHandle(scope.row.n_Id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form label-width="110px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="type" label="类型">
							<el-select :disabled="saveId" v-model="ruleForm.type" placeholder="岗位" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="jobId" label="岗位">
							<el-select v-model="ruleForm.jobId" placeholder="岗位" style="width: 100%" @change="getJobDuty">
								<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="jobResponsibilities" label="岗位职责">
							<el-input v-model="ruleForm.jobResponsibilities" placeholder="岗位职责" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="jobRiskFactors" label="岗位风险因素">
							<el-input type="textarea" v-model="ruleForm.jobRiskFactors" placeholder="岗位风险因素" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="controlMeasures" label="控制措施">
							<el-input type="textarea" v-model="ruleForm.controlMeasures" placeholder="控制措施" clearable />
						</el-form-item>
					</el-col>

					<!-- 现场类才展示 -->
					<template v-if="ruleForm.type == 2">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item prop="" label="工艺流程">
								<el-input type="textarea" v-model="ruleForm.processOperations" placeholder="工艺流程" clearable />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item prop="typeOfAccident" label="事故类型">
								<el-input type="textarea" v-model="ruleForm.typeOfAccident" placeholder="事故类型" clearable />
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 详情 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="dialogVisible" title="详情" width="50%" @close="dialogVisible = false">
			<el-divider content-position="left"> 基本信息 </el-divider>
			<el-descriptions class="margin-top" :column="2" border>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item" style="width: 100px">岗位id</div>
					</template>
					{{ descriptionsData.jobId }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">岗位名称</div>
					</template>
					{{ descriptionsData.jobName }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label>
						<div class="cell-item">岗位种类</div>
					</template>
					{{ descriptionsData.type }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">岗位职责</div>
					</template>
					{{ descriptionsData.jobResponsibilities }}
				</el-descriptions-item>

				<el-descriptions-item :span="2">
					<template #label>
						<div class="cell-item">岗位风险因素</div>
					</template>
					{{ descriptionsData.jobRiskFactors }}
				</el-descriptions-item>
				<el-descriptions-item :span="2">
					<template #label>
						<div class="cell-item">控制措施</div>
					</template>
					{{ descriptionsData.controlMeasures }}
				</el-descriptions-item>

				<el-descriptions-item v-if="descriptionsData.type == 2" :span="2">
					<template #label>
						<div class="cell-item">工艺流程</div>
					</template>
					{{ descriptionsData.processOperations }}
				</el-descriptions-item>
				<el-descriptions-item v-if="descriptionsData.type == 2">
					<template #label>
						<div class="cell-item">事故类型</div>
					</template>
					{{ descriptionsData.typeOfAccident }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label>
						<div class="cell-item">创建人</div>
					</template>
					{{ descriptionsData.createdUserName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">创建时间</div>
					</template>
					{{ descriptionsData.createdTime }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label>
						<div class="cell-item">更新人</div>
					</template>
					{{ descriptionsData.updatedUserName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						<div class="cell-item">更新时间</div>
					</template>
					{{ descriptionsData.updatedTime }}
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import { getJobDutyApi, deleteJobDutyApi, editJobDutyApi, addJobDutyApi, getRiskAssessmentEmployeePostApi, getJobDutyDetailApi } from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
/***** 查询 *****/
let searchObj: any = reactive({});
const transferVal1 = ref();
const transferVal2 = ref();
const searchClick = () => {
	// searchObj.Type = transferVal1.value
	// searchObj.Name = transferVal2.value
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

const resetClick = () => {
	// transferVal1.value = ''
	// transferVal2.value = ''
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};

/***** 新增 *****/
const showDialogVisible = ref(false);
const options1 = [
	{ value: 1, label: '办公室类' },
	{ value: 2, label: '现场类' },
];
const ruleForm = reactive({
	jobId: '', //岗位id 请求/sysPos/list
	name: '', //岗位名称
	type: 1, //办公室类 Office = 1 现场类 Field = 2
	jobResponsibilities: '', //岗位职责
	jobRiskFactors: '', //岗位风险因素
	controlMeasures: '', //控制措施
	processOperations: '', //工艺流程，办公室类不展示这个框，不传这个值
	typeOfAccident: '', //事故类型，办公室类不展示这个框，不传这个值
});
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

const getJobDuty = (val: number) => {
	const item = options2.value.find((element: any) => element.value == val);
	console.log(item);
	ruleForm.name = item.label;
};

/***** 编辑 *****/
const saveId = ref(0);
const nodeClick = async (row: any) => {
	if (row.n_Id) {
		saveId.value = row.n_Id;

		getJobDutyDetailApi({ Id: row.n_Id }).then((res: any) => {
			ruleForm.jobId = res.data.jobId; //岗位id 请求/sysPos/list
			ruleForm.name = res.data.name; //岗位名称
			ruleForm.type = res.data.type; //办公室类 Office = 1 现场类 Field = 2
			ruleForm.jobResponsibilities = res.data.jobResponsibilities; //岗位职责
			ruleForm.jobRiskFactors = res.data.jobRiskFactors; //岗位风险因素
			ruleForm.controlMeasures = res.data.controlMeasures; //控制措施
			ruleForm.processOperations = res.data.processOperations; //工艺流程，办公室类不展示这个框，不传这个值
			ruleForm.typeOfAccident = res.data.typeOfAccident; //事故类型，办公室类不展示这个框，不传这个值

			showDialogVisible.value = true;
		});
	} else {
		showDialogVisible.value = true;
	}
};

/*** 删除 */
const deleteHandle = async (val: String | Number) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: val };
			try {
				let res: any = await deleteJobDutyApi(param);
				if (res.success) {
					getData();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

// 详情
const descriptionsData = ref();
const dialogVisible = ref(false);
const editClick = async (id: any) => {
	const res = await getJobDutyDetailApi({ Id: id });
	descriptionsData.value = res.data;

	dialogVisible.value = true;
};

/***** 新增编辑表单校验和事件 *****/
const ruleFormRef = ref();
const rules = reactive({
	jobId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	type: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	jobResponsibilities: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	jobRiskFactors: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	controlMeasures: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	processOperations: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	typeOfAccident: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});
const cancelUseClick = () => {
	showDialogVisible.value = false;
	saveId.value = 0;

	ruleForm.jobId = ''; //岗位id 请求/sysPos/list
	ruleForm.name = ''; //岗位名称
	ruleForm.type = 1; //办公室类 Office = 1 现场类 Field = 2
	ruleForm.jobResponsibilities = ''; //岗位职责
	ruleForm.jobRiskFactors = ''; //岗位风险因素
	ruleForm.controlMeasures = ''; //控制措施
	ruleForm.processOperations = ''; //工艺流程，办公室类不展示这个框，不传这个值
	ruleForm.typeOfAccident = ''; //事故类型，办公室类不展示这个框，不传这个值

	ruleFormRef.value!.clearValidate();
};
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (saveId.value) {
				editJobDutyApi({ ...ruleForm, id: saveId.value });
			} else {
				addJobDutyApi(ruleForm);
			}
			setTimeout(() => {
				cancelUseClick();
				getData();
			}, 100);
		} else {
			console.log('error submit!', fields);
		}
	});
};

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'type', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'Type', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '类型', // placeholder数据
			defaultProp: options1, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'jobName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'Name', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '岗位名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};


  /*** ================================= 导出数据函数操作 ================================= */
  const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['岗位名称'] = item.jobName ? item.jobName : '-';
                        tableObj['岗位类型'] = item.type == 1 ? '办公' : '现场';

                        tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
                        tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
                        tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
                        tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'岗位职责台账.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getJobDutyApi, {}, searchObj);

const options2: any = ref([]);
onMounted(async () => {
	const res = await getRiskAssessmentEmployeePostApi();
	console.log(res);
	options2.value = res.data.map((item: any) => {
		return {
			value: item.id,
			label: item.name,
		};
	});


    await initInfoFun()
});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
